import { createSelector } from '@reduxjs/toolkit';
import { stateSelector } from 'store/store';
import { useAppSelector } from 'store/storeHooks';
import { defaultSelectorOptions } from 'store/util/defaultMemoizeOptions';

const selector = createSelector(
  [stateSelector],
  (state) => {
    const { generation, system } = state;
    const { model } = generation;

    const { isProcessing, isConnected } = system;

    const reasons: string[] = [];

    // Cannot generate if already processing an image
    if (isProcessing) {
      reasons.push('系统繁忙，请稍等');
    }

    // Cannot generate if not connected
    if (!isConnected) {
      reasons.push('服务未连接');
    }

    if (!model) {
      reasons.push('未选择模型');
    }
    return { isReady: !reasons.length, isProcessing, reasons };
  },
  defaultSelectorOptions
);

export const useIsReadyToInvoke = () => {
  const { isReady, isProcessing, reasons } = useAppSelector(selector);
  return { isReady, isProcessing, reasons };
};
